package com.plugin.sproutcore.util;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

import com.plugin.sproutcore.core.resources.properties.SproutCoreProject;

public class SproutCoreUtil 
{
	// Find all the sproutcore projects in a resource.
	public static IContainer[] getAllSproutCoreProjects(IProject project) 
	throws CoreException
	{
		List<IContainer> scProjects = new ArrayList<IContainer>();
		findSproutCoreProject(project, scProjects);
		return scProjects.toArray(new IContainer[0]);
	}
	
	private static void findSproutCoreProject(IContainer container, 
			List<IContainer> scProjects) 
	throws CoreException
	{
		IResource[] containerMembers = container.members();
		for (IResource resource:containerMembers)
		{
			if (resource instanceof IContainer)
			{
				findSproutCoreProject((IContainer)resource, scProjects);
			}
			else
			{
				String path = resource.getName();
				// SproutCore projects must have a buildFile in it
				if (path.equals("Buildfile")) {
					scProjects.add(resource.getParent());
				}
			}
		}
	}
	
	public static SproutCoreProject createSproutCoreProject(IResource resource)
	{
		IContainer container;
		if (resource instanceof IContainer) {
			container = (IContainer)resource;
		} else {
			container = resource.getParent();
		}
		
		SproutCoreProject scProject = new SproutCoreProject();
		scProject.setName(container.getName());
		scProject.setPath(container.getProjectRelativePath().toPortableString());
		
		return scProject;
	}
}
